var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var YjxBaseModel = require('./YjxBaseModel');
var CONFIG = require('../../config');


var YjxUniItemsModel = function (obj) {
    YjxBaseModel.call(this,obj);

    // 以下为表定义数据
    //`uni_item_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '统一项目id',
    //`item_type` int(2) NOT NULL DEFAULT '0' COMMENT '模版类型:0:未知, 10:单页, 20:PPT, 30:视频',
    //`type_id` bigint(20) DEFAULT NULL COMMENT '模版具体分类 (对应tg_type.type_id顶级分类)',
    //`item_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '项目id: 各种模版的真实id或者商品id (tg_design_doc/itb_tmplate/video_design_doc主键)',
    //`order` int(3) NOT NULL DEFAULT '999' COMMENT '统一模板排序标记',
    //`create_time` datetime NOT NULL COMMENT '创建时间',
    //`update_time` datetime NOT NULL COMMENT '更新时间',
    //`update_by` varchar(50) DEFAULT NULL COMMENT '更新者',
    //`del_flg` int(1) NOT NULL DEFAULT '0' COMMENT '逻辑删除标志位',

};

YjxUniItemsModel.prototype = new YjxBaseModel();

// 取得表名
YjxUniItemsModel.prototype.getTableName = function(){
    return 'yjx_uni_items';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
YjxUniItemsModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'uni_item_id='+this.uni_item_id;
};

/**
 * 获取统一模板预览
 *
 * @author 王俊
 * @date 2017-11-17
 *
 * @param uniId 统一模板 id
 * @param callback  回调
 *          err: 查询失败
 *          results : 对应页信息, 按页码排序
 */
YjxUniItemsModel.prototype.getTemplatePreviewInfo = function (uniId, callback) {

    pool.pool.getConnection(function (getConErr, connection) {
        if(getConErr) {
            console.log('YjxUniItemsModel.js [getTemplatePreviewInfo] getConErr: ' + getConErr);
            return callback(getConErr);
        }
        var sql =
            "	SELECT	" +
            "	  mid.*,	" +
            "	  IF(	" +
            "	    yuts.show_apply_cnt,	" +
            "	    yuts.show_apply_cnt,	" +
            "	    0	" +
            "	  ) AS useCounts	" +
            "	FROM	" +
            "	  (SELECT	" +
            "	    yutd.uni_item_id AS id,	" +
            "	    1 AS opType,	" +
            "	    tdd.design_name AS NAME,	" +
            "	    tdp.thumb,	" +
            "	    ts.width AS w,	" +
            "	    ts.height AS h,	" +
            "	    '' AS videoUrl,	" +
            "	    0 AS duration,	" +
            "	    0 AS fileSize,	" +
            "	    tdp.page_index,	" +
            "	    tdd.data AS `data`,	" +
            "	    tdd.vip,     	" +
            "	    0 AS xmPrice    " +
            "	  FROM	" +
            "	    yjx.yjx_uni_items yutd,	" +
            "	    itbour.tg_design_doc tdd,	" +
            "	    itbour.tg_design_page tdp,	" +
            "	    itbour.tg_size ts	" +
            "	  WHERE yutd.uni_item_id = "+ uniId +"	" +
            "	    AND yutd.item_type = 10	" +
            "	    AND tdd.design_id = yutd.item_id	" +
            "	    AND ts.size_id = tdd.size_id	" +
            "	    AND tdp.design_id = tdd.design_id	" +
            "	    AND yutd.del_flg = 0	" +
            "	    AND tdd.del_flg = 0	" +
            "	    AND tdp.del_flg = 0	" +
            "	    AND ts.del_flg = 0	" +
            "	    AND tdd.publish = 1	" +
            "	  UNION  ALL	" +
            "	  SELECT	" +
            "	    yutd.uni_item_id AS id,	" +
            "	    2 AS opType,	" +
            "	    vdd.design_name AS NAME,	" +
            "	    vdd.theme_thumb AS thumb,	" +
            "	    yvr.w,	" +
            "	    yvr.h,	" +
            "	    yvr.url AS videoUrl,	" +
            "	    yvr.duration,	" +
            "	    yvr.file_size AS fileSize,	" +
            "	    0 AS page_index,	" +
            "	    vdd.tg_data AS `data`,	" +
            "	    vdd.vip,         	" +
            "	    p.unit_pts AS xmPrice   " +
            "	  FROM	" +
            "	    yjx.yjx_uni_items yutd,	" +
            "	    itbour.video_design_doc vdd,	" +
            "	    yjx.yjx_video_res yvr,	" +
            "	    yjx.yjx_price_r pr,	" +
            "	    yjx.yjx_price	p" +
            "	  WHERE yutd.uni_item_id = "+ uniId +"	" +
            "	    AND yutd.item_type = 30	" +
            "	    AND yutd.uni_item_id = pr.uni_item_id	" +
            "	    AND pr.price_id = p.price_id	" +
            "	    AND vdd.design_id = yutd.item_id	" +
            "	    AND yutd.del_flg = 0	" +
            "	    AND vdd.del_flg = 0	" +
            "	    AND pr.del_flg = 0	" +
            "	    AND p.del_flg = 0	" +
            "	    AND vdd.publish = 1	" +
            "	    AND yvr.res_id = vdd.res_low	" +
            "	  UNION  ALL	" +
            "	  SELECT	" +
            "	    yutd.uni_item_id AS id,	" +
            "	    3 AS opType,	" +
            "	    it.tmpl_name AS NAME,	" +
            "	    itp.thumb_s AS thumb,	" +
            "	    1600 AS w,	" +
            "	    900 AS h,	" +
            "	    '' AS videoUrl,	" +
            "	    0 AS duration,	" +
            "	    0 AS fileSize,	" +
            "	    itp.page_index,	" +
            "	    '' AS `data` ,	" +
            "	    it.vip , 	" +
            "	    0 AS xmPrice    " +
            "	  FROM	" +
            "	    yjx.yjx_uni_items yutd,	" +
            "	    itbour.itb_template it,	" +
            "	    itbour.itb_tmpl_page itp	" +
            "	  WHERE yutd.uni_item_id = "+ uniId +"	" +
            "	    AND yutd.item_type = 20	" +
            "	    AND it.tmpl_id = yutd.item_id	" +
            "	    AND itp.tmpl_id = it.tmpl_id	" +
            "	    AND itp.backup_flg = 0	" +
            "	    AND yutd.del_flg = 0	" +
            "	    AND it.del_flg = 0	" +
            "	    AND itp.del_flg = 0	" +
            "	    AND it.publish = 1) MID	" +
            "	  LEFT JOIN yjx.yjx_uni_tmpl_stats yuts	" +
            "	    ON yuts.uni_item_id = mid.id	" +
            "	    AND yuts.del_flg = 0	" +
            "	ORDER BY mid.page_index;	" ;
        console.log(sql);
        connection.query(sql,function (queryErr, results) {
            connection.release();
            return callback(queryErr, results);
        });
    })
};

/**
 * 通过uni_tmpl_id查询模板的yjx_show_type的主键
 * @author 毛凯
 * @date 2017-11-16
 * @param tmplId  模板标识
 * @param callback
 *              qErr  错误信息
 *              res 查询结果（yjx_show_type的主键）
 */
YjxUniItemsModel.prototype.findShowTypeId = function(tmplId, callback){

    // 从mysql中查询
    pool.pool.getConnection(function(getConErr, connection) {
        if (getConErr) {
            console.log('YjxUniTmplDocModel.js [findShowTypeId] getConErr: '+getConErr);
            return callback(getConErr, null);
        }
        var sql = "	SELECT	" +
                "	  st.st_id	" +
                "	FROM	" +
                "	  yjx.yjx_uni_items utd,	" +
                "	  yjx.yjx_tmpl_set_r tsr,	" +
                "	  yjx.yjx_tmpl_set ts,	" +
                "	  yjx.yjx_show_type_r str,	" +
                "	  yjx.yjx_show_type st	" +
                "	WHERE utd.uni_item_id = "+tmplId +"	" +
                "	  AND utd.uni_item_id = tsr.uni_item_id	" +
                "	  AND str.set_id = tsr.set_id	" +
                "	  AND tsr.set_id = ts.set_id	" +
                "	  AND st.st_id = str.st_id	" +
                "	  AND utd.del_flg = 0	" +
                "	  AND tsr.del_flg = 0	" +
                "	  AND ts.del_flg = 0	" +
                "	  AND str.del_flg = 0	" +
                "	  AND st.del_flg = 0	" +
                "	  LIMIT 0,1	" ;
        console.log(sql);
        // Use the connection
        connection.query(sql, function(qErr, res) {
            // And done with the connection.
            connection.release();
            if(qErr) {
                console.log('YjxUniItemsModel.js [findShowTypeId] qErr: '+qErr);
                return callback(qErr);
            }
            // 回调
            callback(qErr, res);
        });
    });
};
/**
 * 查询统一模板的基础信息
 *
 * @author 王俊
 * @date 2017-11-19
 *
 * @param uniId     统一模板 id
 * @param callback  回调
 *          err: 查询失败
 *          data: {
 *              uni_item_id     : 统一模板标识
 *              item_type       : 统一模板类型, 10 设计模板 20 ppt 模板 30 视频模板
 *              item_id         : 模板子表 id(设计模板子表, ppt 模板子表, 视频模板子表)
 *              tmpl_set_id     : 该模板所属模板组 id
 *              tmpl_set_title  : 该模板所属模板组标题
 *              show_type_id    : 该模板所属显示分类 id
 *              show_type_title : 该模板所属显示分类标题,
 *              form_id         : 该模板默认的表单 id
 *          }
 * 注意: 该模板需与某一显示分类相关联
 */
YjxUniItemsModel.prototype.getUniTmplShowTyeInfo = function (uniId, callback) {


    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxUniTmplDocModel.js [getUniTmplBaseInfo] getConErr: ' + getConErr);
            return callback(getConErr, null);
        }
        var sql =
            ' SELECT yutd.uni_item_id, ' +
            '        yutd.item_type, ' +
            '        yutd.item_id, ' +
            '        yts.set_id AS tmpl_set_id, ' +
            '        yts.title AS tmpl_set_title, ' +
            '        yst.st_id AS show_type_id, ' +
            '        yst.title AS show_type_title, ' +
            '        yutd.form_id ' +
            ' FROM yjx.yjx_uni_items yutd, ' +
            '      yjx.yjx_tmpl_set_r ytsr, ' +
            '      yjx.yjx_tmpl_set yts, ' +
            '      yjx.yjx_show_type_r ystr, ' +
            '      yjx.yjx_show_type yst ' +
            ' WHERE yutd.uni_item_id = ' + uniId +
            '   AND ytsr.uni_item_id = yutd.uni_item_id ' +
            '   AND yts.set_id = ytsr.set_id ' +
            '   AND ystr.set_id = ytsr.set_id ' +
            '   AND ystr.st_id = yst.st_id ' +
            '   AND yutd.del_flg=0 ' +
            '   AND ytsr.del_flg=0 ' +
            '   AND yts.del_flg=0 ' +
            '   AND ystr.del_flg=0 ' +
            '   AND yst.del_flg=0 ';
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if(queryErr || !results || results.length <= 0) {
                console.log('YjxUniItemsModel.js [getUniTmplBaseInfo] queryErr: ' + queryErr);
                return callback(queryErr || '该模板不存在或已下架', null);
            }
            return callback(queryErr, results[0]);
        });
    })
};

/**
 * 获取 统一商品表内项目的设计项目的基础信息
 *
 * @author 王俊
 * @date 2017-11-25
 *
 * @param uniId     统一商品表 id
 * @param callback  回调
 *          error: 查询失败
 *          data: [{
 *               "id": 3649,
 *               "name": "黄色可爱母婴用品名片",
 *               "opType": 1,
 *               "thumb": "http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U408535/2017/10/19/141013141_s0Fdgn13gtHCFehFbuZm/0.jpg",
 *               "w": 1134,
 *               "h": 709,
 *               "author": "李国梅",
 *               "time": "2017-10-19 12:05:53",
 *               "typeDesc": "印品",
 *               "order": 999,
 *               "useCounts": 0
 *        }]
 * 注意:
 * 1. 统一商品需与 show_type 关联
 * 2. 此方法只查询统一商品对应的设计模板信息, 即该 uniId 对应的 item_type = 10
 * 3. 如果获取不到则返回失败
 */
YjxUniItemsModel.prototype.getUniItemDesignBaseInfos = function (uniId, callback) {
    pool.pool.getConnection(function (getConErr, connection) {
        if(getConErr) {
            console.log('YjxUniItemsModel.js [getUniItemDesignBaseInfo] getConErr: ' + getConErr);
            return callback(getConErr, null);
        }
        var sql = ' SELECT mid.*, ' +
            '        if(yuts.show_apply_cnt IS NOT NULL, yuts.show_apply_cnt, 0) AS useCounts ' +
            ' FROM ' +
            '   (SELECT yui.uni_item_id AS id, ' +
            '           1 AS opType, ' +
            '           tdd.design_name AS name, ' +
            '           tdp.thumb, ' +
            '           ts.width AS w, ' +
            '           ts.height AS h, ' +
            '           DATE_FORMAT(tdd.create_time,"%Y-%m-%d %H:%i:%s") AS time, ' +   // 创建时间
            '           DATE_FORMAT(tdd.update_time,"%Y-%m-%d %H:%i:%s") AS upTime, ' + // 更新时间
            '           tdd.create_time, ' +
            '           tdd.update_time, ' +
            '           tdd.order, ' +
            '           iu.nickname AS author, ' +
            '           yst.title AS typeDesc, ' +
            '           yst.st_id, ' +
            '           yts.set_id ' +
            '    FROM yjx.yjx_uni_items yui, ' +
            '         itbour.tg_design_doc tdd, ' +
            '         itbour.tg_design_page tdp, ' +
            '         itbour.tg_size ts, ' +
            '         itbour.itb_user iu, ' +
            '         yjx.yjx_tmpl_set_r ytsr, ' +
            '         yjx.yjx_tmpl_set yts, ' +
            '         yjx.yjx_show_type_r ystr, ' +
            '         yjx.yjx_show_type yst ' +
            '    WHERE yui.uni_item_id = ' + uniId +
            '      AND yui.item_type = 10 ' +
            '      AND yui.del_flg=0 ' +
            '      AND tdd.design_id = yui.item_id ' +
            '      AND tdd.publish = 1 ' +
            '      AND tdd.ver>2 ' +    // 版本过低的模板不加入缓存
            '      AND tdd.del_flg=0 ' +
            '      AND tdp.design_id = tdd.design_id ' +
            '      AND tdp.page_index = 0 ' +
            '      AND tdp.del_flg = 0 ' +
            '      AND ts.size_id = tdd.size_id ' +
            '      AND ts.del_flg = 0 ' +
            '      AND iu.user_id = tdd.user_id ' +
            '      AND iu.del_flg = 0 ' +
            '      AND ytsr.uni_item_id = yui.uni_item_id ' +
            '      AND ytsr.del_flg = 0 ' +
            '      AND ytsr.set_id = yts.set_id ' +
            '      AND yts.del_flg = 0 ' +
            '      AND ystr.set_id = yts.set_id ' +
            '      AND ystr.del_flg = 0 ' +
            '      AND yst.st_id = ystr.st_id ' +
            '      AND yst.del_flg = 0) mid ' +
            ' LEFT JOIN yjx.yjx_uni_tmpl_stats yuts ON yuts.uni_item_id = mid.id ' +
            ' AND yuts.del_flg=0 ';
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if(queryErr || !results || results.length <=0) {
                console.log('YjxUniItemsModel.js [getUniItemDesignBaseInfo] queryErr: ' + queryErr || '暂无该商品信息');
                return callback(queryErr || '该模板不存在或已下架', null);
            }
            return callback(queryErr, results);
        });
    })
};

/**
 * 获取 统一商品表内项目的视频项目的基础信息
 *
 * @author 王俊
 * @date 2017-11-25
 *
 * @param uniId     统一商品表 id
 * @param callback  回调
 *          error: 查询失败
 *          data: [{
 *               "id": 3649,
 *               "name": "黄色可爱母婴用品名片",
 *               "opType": 1,
 *               "thumb": "http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U408535/2017/10/19/141013141_s0Fdgn13gtHCFehFbuZm/0.jpg",
 *               "w": 1134,
 *               "h": 709,
 *               "author": "李国梅",
 *               "time": "2017-10-19 12:05:53",
 *               "typeDesc": "印品",
 *               "order": 999,
 *               "useCounts": 0
 *        }]
 * 注意:
 * 1. 统一商品需与 show_type 关联
 * 2. 此方法只查询统一商品对应的设计模板信息, 即该 uniId 对应的 item_type = 30
 * 3. 如果获取不到则返回失败
 */
YjxUniItemsModel.prototype.getUniItemVideoBaseInfos = function (uniId, callback) {
    pool.pool.getConnection(function (getConErr, connection) {
        if(getConErr) {
            console.log('YjxUniItemsModel.js [getUniItemVideoBaseInfo] getConErr: ' + getConErr);
            return callback(getConErr, null);
        }
        var sql = ' SELECT mid.*, ' +
            '        if(yuts.show_apply_cnt IS NOT NULL, yuts.show_apply_cnt, 0) AS useCounts ' +
            ' FROM ' +
            '   ( SELECT yui.uni_item_id AS id, ' +
            '            2 AS opType, ' +
            '            vdd.design_name AS name, ' +
            '            vdd.theme_thumb AS thumb, ' +
            '            ts.width AS w, ' +
            '            ts.height AS h, ' +
            '            DATE_FORMAT(vdd.create_time,"%Y-%m-%d %H:%i:%s") AS time, ' +
            '            DATE_FORMAT(vdd.update_time,"%Y-%m-%d %H:%i:%s") AS upTime, ' +
            '            vdd.create_time, ' +
            '            vdd.update_time, ' +
            '            vdd.order, ' +
            '            iu.nickname AS author, ' +
            '            yst.title AS typeDesc, ' +
            '            yst.st_id, ' +
            '            yts.set_id ' +
            '    FROM yjx.yjx_uni_items yui, ' +
            '         itbour.video_design_doc vdd, ' +
            '         itbour.tg_size ts, ' +
            '         itbour.itb_user iu, ' +
            '         yjx.yjx_tmpl_set_r ytsr, ' +
            '         yjx.yjx_tmpl_set yts, ' +
            '         yjx.yjx_show_type_r ystr, ' +
            '         yjx.yjx_show_type yst ' +
            '    WHERE yui.uni_item_id = ' + uniId +
            '      AND yui.item_type = 30 ' +
            '      AND yui.del_flg=0 ' +
            '      AND vdd.design_id = yui.item_id ' +
            '      AND vdd.publish = 1 ' +
            '      AND vdd.del_flg=0 ' +
            '      AND ts.size_id = vdd.size_id ' +
            '      AND ts.del_flg = 0 ' +
            '      AND iu.user_id = vdd.user_id ' +
            '      AND iu.del_flg = 0 ' +
            '      AND ytsr.uni_item_id = yui.uni_item_id ' +
            '      AND ytsr.del_flg = 0 ' +
            '      AND ytsr.set_id = yts.set_id ' +
            '      AND yts.del_flg = 0 ' +
            '      AND ystr.set_id = yts.set_id ' +
            '      AND ystr.del_flg = 0 ' +
            '      AND yst.st_id = ystr.st_id ' +
            '      AND yst.del_flg = 0 ) mid ' +
            ' LEFT JOIN yjx.yjx_uni_tmpl_stats yuts ON yuts.uni_item_id = mid.id ' +
            ' AND yuts.del_flg=0 ';
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if(queryErr || !results || results.length <=0) {
                console.log('YjxUniItemsModel.js [getUniItemVideoBaseInfo] queryErr: ' + queryErr || '暂无该商品信息');
                return callback(queryErr || '该模板不存在或已下架', null);
            }
            return callback(queryErr, results);
        });
    })
};

/**
 * 获取 统一商品表内项目的PPT项目的基础信息
 *
 * @author 王俊
 * @date 2017-11-25
 *
 * @param uniId     统一商品表 id
 * @param callback  回调
 *          error: 查询失败
 *          data: [{
 *               "id": 3649,
 *               "name": "黄色可爱母婴用品名片",
 *               "opType": 1,
 *               "thumb": "http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U408535/2017/10/19/141013141_s0Fdgn13gtHCFehFbuZm/0.jpg",
 *               "w": 1134,
 *               "h": 709,
 *               "author": "李国梅",
 *               "time": "2017-10-19 12:05:53",
 *               "typeDesc": "印品",
 *               "order": 999,
 *               "useCounts": 0
 *        }]
 * 注意:
 * 1. 统一商品需与 show_type 关联
 * 2. 此方法只查询统一商品对应的设计模板信息, 即该 uniId 对应的 item_type = 20
 * 3. 如果获取不到则返回失败
 */
YjxUniItemsModel.prototype.getUniItemPPTBaseInfos = function (uniId, callback) {
    pool.pool.getConnection(function (getConErr, connection) {
        if(getConErr) {
            console.log('YjxUniItemsModel.js [getUniItemPPTBaseInfo] getConErr: ' + getConErr);
            return callback(getConErr, null);
        }
        var sql = ' SELECT mid.*, ' +
            '        if(yuts.show_apply_cnt IS NOT NULL, yuts.show_apply_cnt, 0) AS useCounts ' +
            ' FROM ' +
            '   ( SELECT yui.uni_item_id AS id, ' +
            '            3 AS opType, ' +
            '            it.tmpl_name AS name, ' +
            '            itp.thumb_s AS thumb, ' +
            '            1600 AS w, ' +
            '            900 AS h, ' +
            '            DATE_FORMAT(it.create_time,"%Y-%m-%d %H:%i:%s") AS time, ' +
            '            DATE_FORMAT(it.update_time,"%Y-%m-%d %H:%i:%s") AS upTime, ' +
            '            it.create_time, ' +
            '            it.update_time, ' +
            '            it.order, ' +
            '            iu.nickname AS author, ' +
            '            yst.title AS typeDesc, ' +
            '            yst.st_id, ' +
            '            yts.set_id ' +
            '    FROM yjx.yjx_uni_items yui, ' +
            '         itbour.itb_template it, ' +
            '         itbour.itb_tmpl_page itp, ' +
            '         itbour.itb_user iu, ' +
            '         yjx.yjx_tmpl_set_r ytsr, ' +
            '         yjx.yjx_tmpl_set yts, ' +
            '         yjx.yjx_show_type_r ystr, ' +
            '         yjx.yjx_show_type yst ' +
            '    WHERE yui.uni_item_id = ' + uniId +
            '      AND yui.item_type = 20 ' +
            '      AND yui.del_flg=0 ' +
            '      AND it.tmpl_id = yui.item_id ' +
            '      AND it.publish = 1 ' +
            '      AND it.del_flg=0 ' +
            '      AND itp.tmpl_id = it.tmpl_id ' +
            '      AND itp.page_index = 0 ' +
            '      AND itp.del_flg=0 ' +
            '      AND iu.user_id = it.user_id ' +
            '      AND iu.del_flg = 0 ' +
            '      AND ytsr.uni_item_id = yui.uni_item_id ' +
            '      AND ytsr.del_flg = 0 ' +
            '      AND ytsr.set_id = yts.set_id ' +
            '      AND yts.del_flg = 0 ' +
            '      AND ystr.set_id = yts.set_id ' +
            '      AND ystr.del_flg = 0 ' +
            '      AND yst.st_id = ystr.st_id ' +
            '      AND yst.del_flg = 0 ) mid ' +
            ' LEFT JOIN yjx.yjx_uni_tmpl_stats yuts ON yuts.uni_item_id = mid.id ' +
            ' AND yuts.del_flg=0 ';
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if(queryErr || !results || results.length <=0) {
                console.log('YjxUniItemsModel.js [getUniItemPPTBaseInfo] queryErr: ' + queryErr || '暂无该商品信息');
                return callback(queryErr || '该模板不存在或已下架', null);
            }
            return callback(queryErr, results);
        });
    })
};

/**
 * 获取统一商品的 keyword 信息
 *
 * @author 王俊
 * @date 2017-11-25
 *
 * @param uniId     统一商品标识
 * @param callback  回调
 *          err: 查询失败
 *          data: {
 *             unknown : [],    // 未知 关键词数组
 *             industry : [],   // 行业 关键词数组
 *             scene : [],      // 场景 关键词数组
 *             style : [],      // 设计风格 关键词数组
 *             custom : []      // 自定义 关键词数组
 *          }
 * 注意:
 * 1. 0未知,1行业,2场景,3设计风格,10自定义
 */
YjxUniItemsModel.prototype.getUniItemKeywordInfo = function (uniId, callback) {

    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxUniItemsModel.js [getUniItemKeywordInfo] getConErr: ' + getConErr);
            return callback(getConErr, null);
        }

        var sql = ' SELECT tk.type, ' +
            '        tk.key_name ' +
            ' FROM yjx.yjx_uni_items yui, ' +
            '      itbour.tg_keyword_r tkr, ' +
            '      itbour.tg_keyword tk ' +
            ' WHERE yui.uni_item_id = ' + uniId +
            '   AND yui.del_flg=0 ' +
            '   AND tkr.doc_id = yui.item_id ' +
            '   AND tkr.type_id = yui.type_id ' +
            '   AND tkr.del_flg=0 ' +
            '   AND tk.key_id = tkr.key_id ' +
            '   AND tk.del_flg=0 ' +
            ' ORDER BY tk.type ';
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if(queryErr) {
                console.log('YjxUniItemsModel.js [getUniItemKeywordInfo] queryErr: ' + queryErr);
                return callback(queryErr, null);
            }
            var retData = {
                unknown : [],
                industry : [],
                scene : [],
                style : [],
                custom : []
            };
            if(results && results.length > 0) {
                for(var i=0; i < results.length; i++) {
                    var type = Number(results[i].type);
                    var kwd = results[i].key_name;
                    if(!kwd || kwd.length <=0) {
                        continue;
                    }
                    // 0未知,1行业,2场景,3设计风格,10自定义
                    if(type === 0) {
                        retData.unknown.push(kwd);
                    } else if(type === 1) {
                        retData.industry.push(kwd);
                    } else if(type === 2) {
                        retData.scene.push(kwd);
                    } else if(type === 3) {
                        retData.style.push(kwd);
                    } else if(type === 10) {
                        retData.custom.push(kwd);
                    }
                }
            }
            return callback(queryErr, retData);
        });
    });
};

/**
 * 获取uni_item_id
 * @author 毛凯
 * @date   2018-1-22
 * @param itemId 商品id
 * @param itemType 商品类型
 * @param callback 回调
 *                err:错误信息
 *                data:返回数据
 * */

YjxUniItemsModel.prototype.getUniItemId = function(itemId,itemType,callback){
    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxUniItemsModel.getUniItemId getUniItemId: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        //查询userId对应的所有第三方信息
        var sql= "SELECT uni_item_id FROM yjx.yjx_uni_items WHERE item_id = "+itemId+" AND item_type = "+itemType;
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxUniItemsModel.getUniItemId Err: ' + error);
                return callback(error, null);
            }
            if(results){
                return callback(null, results);
            }else{
                return callback(null, null);
            }
        })
    })
};


/**
 * 获取vip商品信息
 * @author 毛凯
 * @date   2018-3-24
 * @param callback 回调
 *                err:错误信息
 *                data:返回数据
 * */

YjxUniItemsModel.prototype.getUniItemVipInfo = function(callback){
    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxUniItemsModel.getUniItemId getUniItemVipInfo: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        //查询vip商品
        var sql= "SELECT	" +
            "	  yui.uni_item_id ,	" +
            "	  p.show_name as `name`,	" +
            "	  p.desc ,	" +
            "	  p.price_id AS id,	" +
            "	  p.pay_type as payType,	" +
            "	  p.unit_price as payPrice,	" +
            "	  p.unit_pts as payPoints,	" +
            "	  p.price_type as  earnService,	" +
            "	  p.qty as earnQty,	" +
            "	  p.unit as earnUnit,	" +
            "	  p.order,	" +
            "	  yg.goods_name as itemName,	" +
            "	  yg.desc as itemDesc	" +
            "	FROM	" +
            "	  yjx.yjx_uni_items yui,	" +
            "	  yjx.yjx_price_r  ypr,	" +
            "	  yjx.yjx_goods yg,	" +
            "	  yjx.yjx_price  p	" +
            "	WHERE yg.goods_type = 10	" +
            "	and yui.item_id = yg.goods_id	" +
            "	AND yui.uni_item_id = ypr.uni_item_id	" +
            "	AND ypr.price_id = p.price_id	" +
            "	and yg.state = 20	" +
            "	and p.state = 10	" +
            "	AND yui.del_flg = 0	" +
            "	AND ypr.del_flg = 0	" +
            "	AND p.del_flg = 0	" ;
            console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxUniItemsModel.getUniItemId Err: ' + error);
                return callback(error, null);
            }
            if(results){
                return callback(null, results);
            }else{
                return callback(null, null);
            }
        })
    })
};

/**
 * 获取统一项目对应模板组的 id(非专题)
 *
 * @author 王俊
 * @date 2018-04-17
 *
 * @param uniDocId 统一项目 id
 * @param callback 回调
 *          err: 查询失败
 *          sets: 模板组行数组
 */
YjxUniItemsModel.prototype.getUniItemTmplSets = function (uniDocId, callback) {
    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxUniItemsModel.getUniItemTmplSets conErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql=
            ' SELECT yts.* ' +
            ' FROM yjx.yjx_uni_items yui, ' +
            '      yjx.yjx_tmpl_set_r ytsr, ' +
            '      yjx.yjx_tmpl_set yts ' +
            ' WHERE yui.del_flg=0 ' +
            '   AND yui.uni_item_id = ' + uniDocId +
            '   AND ytsr.del_flg=0 ' +
            '   AND ytsr.uni_item_id = yui.uni_item_id ' +
            '   AND yts.del_flg=0 ' +
            '   AND yts.set_id = ytsr.set_id ' +
            '   AND yts.use = 0 ' +
            '   ORDER BY ytsr.create_time DESC ';
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxUniItemsModel.getUniItemTmplSets queryErr: ' + error);
                return callback(error, null);
            }
            return callback(error, results);
        })
    })
};


/**
 * 获取充值商品信息
 * @author 毛凯
 * @date   2018-5-15
 * @param callback 回调
 *                err:错误信息
 *                data:返回数据
 * */

YjxUniItemsModel.prototype.getRechargeInfo = function(callback){
    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxUniItemsModel.getUniItemId getUniItemVipInfo: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        //查询充值套餐商品
        var sql= "	SELECT	" +
            "	  yui.uni_item_id,	" +
            "	  p.show_name AS `name`,	" +
            "	  p.desc,	" +
            "	  p.price_id AS id,	" +
            "	  p.pay_type AS payType,	" +
            "	  p.unit_price AS payPrice,	" +
            "	  p.unit_pts AS payPoints,	" +
            "	  p.price_type AS earnService,	" +
            "	  p.qty AS earnQty,	" +
            "	  p.unit AS earnUnit,	" +
            "	  p.order,	" +
            "	  yg.goods_name AS itemName,	" +
            "	  yg.desc AS itemDesc	" +
            "	FROM	" +
            "	  yjx.yjx_uni_items yui,	" +
            "	  yjx.yjx_price_r ypr,	" +
            "	  yjx.yjx_goods yg,	" +
            "	  yjx.yjx_price p	" +
            "	WHERE yg.goods_type = 20	" +
            "	  AND yg.retail = 10	" +
            "	  AND yui.item_id = yg.goods_id	" +
            "	  AND yui.uni_item_id = ypr.uni_item_id	" +
            "	  AND ypr.price_id = p.price_id	" +
            "	  AND yg.state = 20	" +
            "	  AND p.state = 10	" +
            "	  AND p.price_type = 16	" +
            "	  AND yui.del_flg = 0	" +
            "	  AND ypr.del_flg = 0	" +
            "	  AND p.del_flg = 0;	" ;
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxUniItemsModel.getUniItemId Err: ' + error);
                return callback(error, null);
            }
            if(results){
                return callback(null, results);
            }else{
                return callback(null, null);
            }
        })
    })
};


/**
 * 获取音频列表sql
 *
 * @author 毛凯
 * @date 2018-07-4
 *
 * @param bForCnt 标记查询个数还是列表
 * @param pageNum 页码
 * @param pageSize 页容量
 * @param sql
 */
function sql_getMediaList(bForCnt,pageNum,pageSize) {
    var sql = '';
    if(bForCnt) {
        sql += " SELECT " +
            "   COUNT(0) AS `count` ";
    } else  {
        sql +="	SELECT	" +
            "	  yui.uni_item_id AS id,	" +
            "	  im.media_name AS `name`,	" +
            "	  im.url ,	" +
            "	  im.duration,	" +
            "	  IFNULL(itbour.func_parse_string_array(im.thumbs,0),'') AS thumb	" ;
    }
    sql += "	FROM	" +
        "	  yjx.yjx_uni_items yui,	" +
        "	  yjx.yjx_tmpl_set_r ytsr,	" +
        "	  yjx.yjx_tmpl_set yts,	" +
        "	  itbour.itb_media im	" +
        "	  WHERE yui.uni_item_id = ytsr.uni_item_id	" +
        "	  AND   ytsr.set_id = yts.set_id	" +
        "	  AND  yts.use = 30	" +
        "	  AND yui.item_id = im.media_id	" +
        "	  AND yui.del_flg = 0	" +
        "	  AND im.media_type = 10  " +
        "	  AND im.use = 20	" +
        "	  AND ytsr.del_flg = 0	" +
        "	  AND yts.publish = 1	" +
        "	  AND yts.del_flg = 0	" +
        "	  AND im.del_flg = 0	" +
        "	  ORDER BY im.order ASC , im.create_time DESC	" ;
    if (!bForCnt) {
        if (typeof pageNum !== 'undefined' && pageNum !== null &&
            typeof pageSize !== 'undefined' && pageSize !== null)
        {
            var skipCnt = Number(pageNum||'0') * Number(pageSize||'0');
            sql += " LIMIT " + skipCnt + "," + Number(pageSize||'0');
        }
    }
    return sql;
}



/**
 * 获取音频列表sql
 *
 * @author 毛凯
 * @date 2018-6-11
 *
 * @param pageNum 页码
 * @param pageSize 页容量
 * @param callback 回调
 *           err: 查询失败
 *           results: 活动列表
 *
 * */
YjxUniItemsModel.prototype.getMediaList = function (pageNum,pageSize,callback){
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxActivityModel.js [getActivityList] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getMediaList(false,pageNum,pageSize);
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxActivityModel.js [getActivityList] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    })
};
/**
 * 获取音频列表数量
 *
 * @author 毛凯
 * @date 2018-7-4
 *
 * @param pageNum 页码
 * @param pageSize 页容量
 * @param callback 回调
 *           err: 查询失败
 *           results: 活动列表
 *
 * */
YjxUniItemsModel.prototype.getMediaListCnt = function (pageNum,pageSize,callback){
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxActivityModel.js [getActivityListCnt] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getMediaList(true,pageNum,pageSize);
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxActivityModel.js [getActivityListCnt] queryErr' + queryErr)
            }
            return callback(queryErr, results[0].count);
        });
    })
};




module.exports = YjxUniItemsModel;

